package com.mystore.filter;

import com.mystore.servlet.UserServlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
//y用户拦截器
@WebFilter(filterName = "UserFilter",urlPatterns = {"/check/*"})
public class UserFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        String encoding = "UTF-8";
        request.setCharacterEncoding(encoding);
        HttpSession session = request.getSession();
        HttpServletResponse response = (HttpServletResponse)resp;
        response.setContentType("text/html;charset="+encoding);
        PrintWriter out = response.getWriter();
        StringBuffer url = request.getRequestURL();
        System.out.println("url="+url);
        Object object= session.getAttribute(UserServlet.USER);
        if(object==null){
            //如果没有登录,会让其先登录后操作,重定向到登录页面
            out.println("你尚未登录,请先登录");
            response.setHeader("refresh","2;url=/login.jsp");
        }



        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
